package com.spzx.order.reveiver;

import com.rabbitmq.client.Channel;
import com.spzx.order.configure.DeadLetterMqConfig;
import com.spzx.order.configure.DelayedMqConfig;
import com.spzx.rabbit.constant.MqConst;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class TestReceiver {

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TEST,durable = "true"),
            value = @Queue(value=MqConst.QUEUE_TEST,durable = "true"),
            key = {MqConst.ROUTING_TEST}
    ))
    public void a(Channel channel, Message message,String msg) throws Exception{
        byte[] body = message.getBody();
        String bodyStr = new String(body);
        System.out.println(bodyStr);
        System.out.println(msg);
        // 默认自动应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);// 手动应答,非批量确认
    }

    @SneakyThrows
    @RabbitListener(queues = {DeadLetterMqConfig.queue_dead_2})
    public void getDeadLetterMsg(String msg, Message message, Channel channel) {
        log.info("死信消费者：{}", msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    //监听延迟消息
    @SneakyThrows
    @RabbitListener(queues = {DelayedMqConfig.queue_delay_1})
    public void getDelayedMsg(String msg, Message message, Channel channel) {
        //接收消息，消费者端判断是否需要做幂等性处理，如果业务保证幂等性，基于redis setnx保证
        String key = "mq:" + msg;
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


}
